package com.stox.core.dao.mapper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.stox.core.model.Scrip;

public class ScripRowMapper implements RowMapper<Scrip> {

	public static final String createSql = "create table scrip(" +
			"id varchar(100), " +
			"code varchar(20) not null," +
			"name varchar(300) not null," +
			"exchangeCode varchar(20) not null," +
			"minDate date," +
			"maxDate date," +
			"scrip_type varchar(20)," +
			"scrip_group varchar(20)," +
			"primary key (code))";
	public static final String createIndexSql = "create unique index scripindex on scrip(code)";
	public static final String selectSql = "select s.id, s.code, s.name, s.exchangeCode, s.minDate, s.maxDate, s.scrip_type, s.scrip_group from scrip s ";
	public static final String insertSql = "insert into scrip(id, code, name, exchangeCode, minDate, maxDate, scrip_type, scrip_group) values (?,?,?,?,?,?,?,?);";
	
	@Override
	public List<Scrip> map(ResultSet rs) throws SQLException {
		List<Scrip> scripList = new ArrayList<Scrip>();
		while(rs.next()){
			Scrip scrip = new Scrip();
			scrip.setId(rs.getString("id"));
			scrip.setCode(rs.getString("code"));
			scrip.setName(rs.getString("name"));
			scrip.setExchangeCode(rs.getString("exchangeCode"));
			if(rs.getDate("minDate") != null){
				scrip.setMinDate(new Date(rs.getDate("minDate").getTime()));
			}
			if(rs.getDate("maxDate") != null){
				scrip.setMaxDate(new Date(rs.getDate("maxDate").getTime()));
			}
			scrip.setType(rs.getString("scrip_type"));
			scrip.setGroup(rs.getString("scrip_group"));
			scripList.add(scrip);
		}
		return scripList;
	}

	public void map(PreparedStatement ps, Scrip scrip) throws SQLException{
		ps.setString(1, scrip.getId());
		ps.setString(2, scrip.getCode());
		ps.setString(3, scrip.getName());
		ps.setString(4, scrip.getExchangeCode());
		if(scrip.getMinDate() == null){
			ps.setDate(5, null);
		}else{
			ps.setDate(5, new java.sql.Date(scrip.getMinDate().getTime()));
		}
		if(scrip.getMaxDate() == null){
			ps.setDate(6, null);
		}else{
			ps.setDate(6, new java.sql.Date(scrip.getMaxDate().getTime()));
		}
		ps.setString(7, scrip.getType());
		ps.setString(8, scrip.getGroup());
	}
	
}
